package com.example.assisteddriving;

import static android.content.Context.MODE_PRIVATE;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.assisteddriving.service.AnalyseSevice;
import com.example.assisteddriving.service.Callservice;
import com.example.assisteddriving.service.Jiujiasevice;
import com.example.assisteddriving.service.Xinlvservice;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Zhuye extends Fragment {
    private static final int REQUEST_CODE = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.CALL_PHONE"};
    LinearLayout ditu,xinlv;
    Switch yuyinsw,hujiaosw;
    TextView paomadeng;
    public static Handler myHandler;
    public static final String PREFERENCE_NAME = "gerenxinxi";  //文件名
    public static int MODE = MODE_PRIVATE;  //操作模式
    Intent jiujiaintent,dituintent,xinlvintent;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.zhuye,null);

        initview(view);

        myHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle data = msg.getData();
                switch (msg.what){
                    case 0x001:
                        yuyinsw.setChecked(false);
                        break;
                    case 0x002:
                        hujiaosw.setChecked(false);
                        break;
                }
            }
        };
        return view;
    }

    private void initview(View view) {
        paomadeng=view.findViewById(R.id.text);
        paomadeng.setSelected(true);
        xinlv=view.findViewById(R.id.xinlv);
        xinlv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermission3();

            }
        });

        ditu=view.findViewById(R.id.ditu);
        ditu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermission2();

            }
        });
        yuyinsw=view.findViewById(R.id.yuyinsw);
        hujiaosw=view.findViewById(R.id.hujiaosw);
        yuyinsw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //控制开关字体颜色
                Intent callintent=new Intent(getActivity(), Callservice.class);
                Intent anintent=new Intent(getActivity(), AnalyseSevice.class);
                if (b) {
                    yuyinsw.setSwitchTextAppearance(getActivity(),R.style.s_true);

                    getActivity().startService(callintent);
                    getActivity().startService(anintent);
                }else {
                    yuyinsw.setSwitchTextAppearance(getActivity(),R.style.s_false);
                    // Toast.makeText(getActivity(),"紧急通话关闭",Toast.LENGTH_LONG).show();
                    getActivity().stopService(callintent);
                    getActivity().stopService(anintent);
                }
            }
        });
        hujiaosw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b) {
                    hujiaosw.setSwitchTextAppearance(getActivity(),R.style.s_true);
                    checkPermission();//电话权限
                    jiujiaintent=new Intent(getActivity(), Jiujiasevice.class);
                    getActivity().startService(jiujiaintent);
                }else {
                    hujiaosw.setSwitchTextAppearance(getActivity(),R.style.s_false);
                    // Toast.makeText(getActivity(),"紧急通话关闭",Toast.LENGTH_LONG).show();
                    getActivity().stopService(jiujiaintent);
                }
            }
        });
    }
    private void checkPermission3(){
        if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){//未开启定位权限
            //开启定位权限,200是标识码
            Log.v("asd","定位申请");
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},3);
        }else{
            Log.v("asd","定位已授权");
            xinlvintent=new Intent(getActivity(), Xinlv.class);
            getActivity().startActivity(xinlvintent);
        }
    }
//dingweiqianxian
    private void checkPermission2(){
        if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){//未开启定位权限
            //开启定位权限,200是标识码
            Log.v("asd","定位申请");
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},2);
        }else{
            Log.v("asd","定位已授权");
            dituintent = new Intent(getActivity(),Map.class);
            startActivity(dituintent);
        }
    }

    //打电话的权限申请
    private void checkPermission() {
        //权限是否已经赋予
        if (ActivityCompat.checkSelfPermission(getActivity(), PERMISSIONS_STORAGE[0]) != PackageManager.PERMISSION_GRANTED) {
            Log.v("asd","申请电话");
            requestPermissions( PERMISSIONS_STORAGE, REQUEST_CODE);
        } else {
            //权限已赋予
            Log.v("asd","电话已授权");
            SharedPreferences sharedPreferences = getContext().getSharedPreferences(PREFERENCE_NAME, MODE);
            String phoneNuml = sharedPreferences.getString("jinjidianhua", null);
            if (phoneNuml==null&&sharedPreferences.getString("xingming",null)==null){
                hujiaosw.setChecked(false);
                AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                        //标题
                        .setTitle("提示")
                        //内容
                        .setMessage("请前往“个人信息“界面完善个人信息")
                        //图标
                        .setIcon(R.mipmap.ic_launcher)
                        .setPositiveButton("确认", null)
                        .create();
                alertDialog.show();
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            //权限的申请结果返回
            case REQUEST_CODE: {
                if (grantResults.length > 0&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    SharedPreferences sharedPreferences = getContext().getSharedPreferences(PREFERENCE_NAME, MODE);
                    String phoneNuml = sharedPreferences.getString("jinjidianhua", null);
                    if (phoneNuml==null&&sharedPreferences.getString("xingming",null)==null){
                        hujiaosw.setChecked(false);
                        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                                //标题
                                .setTitle("提示")
                                //内容
                                .setMessage("请前往“个人信息“界面完善个人信息")
                                //图标
                                .setIcon(R.mipmap.ic_launcher)
                                .setPositiveButton("确认", null)
                                .create();
                        alertDialog.show();
                    }

                } else {
                    hujiaosw.setChecked(false);
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                            //标题
                            .setTitle("提示")
                            //内容
                            .setMessage("请在设置中为此应用提供”拨打电话“权限")
                            //图标
                            .setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确认", null)
                            .create();
                            alertDialog.show();
                }
                break;
            }
            case 2: {
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){//用户同意权限,执行我们的操作
                    dituintent = new Intent(getActivity(), Map.class);
                    startActivity(dituintent);
                }else{//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                            //标题
                            .setTitle("提示")
                            //内容
                            .setMessage("请在设置中为此应用提供”定位“权限")
                            //图标
                            .setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确认", null)
                            .create();
                    alertDialog.show();
                }
                break;
            }
            case 3: {
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){//用户同意权限,执行我们的操作
                    xinlvintent=new Intent(getActivity(), Xinlv.class);
                    getActivity().startActivity(xinlvintent);
                }else{//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                            //标题
                            .setTitle("提示")
                            //内容
                            .setMessage("请在设置中为此应用提供”定位“权限")
                            //图标
                            .setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确认", null)
                            .create();
                    alertDialog.show();
                }
                break;
            }
        }
    }
}
